<template>
  <div class="category-container">
    <div class="header">
      <el-button type="primary" @click="handleAdd">新增分类</el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column  label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)"
            :disabled="scope.row.status === 0">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination v-model="pageParams.page" :page-size="pageParams.size" :total="total"
        :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" @update:page-size="val => pageParams.size = val" />
    </div>

    <el-dialog v-model="dialogVisible" :title="form.id ? '编辑分类' : '新增分类'" width="500px">
      <el-form :model="form" label-width="80px" ref="formRef" :rules="rules">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入分类描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 数据列表
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const pageParams = ref({
  page: 1,
  size: 10
})

// 表单数据
const dialogVisible = ref(false)
const formRef = ref(null)
const form = ref({
  id: null,
  name: '',
  description: ''
})

//判断是否为管理员
const isAdmin = computed(() => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  return userInfo.role == 'admin'
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 获取分类列表
const getList = async (forceRefresh = false) => {
  loading.value = true
  try {
    console.log('获取分类列表, 页码:', pageParams.value.page, '每页大小:', pageParams.value.size, forceRefresh ? '(强制刷新)' : '')

    const params = {
      page: pageParams.value.page - 1, // 后端分页从0开始
      size: pageParams.value.size
    }

    // 如果需要强制刷新，添加时间戳参数
    if (forceRefresh) {
      params._t = new Date().getTime()
    }

    const res = await request.get('/categories', { params })

    if (res && res.code === 200 && res.data) {
      // 确保返回的数据是有效的数组
      tableData.value = Array.isArray(res.data.content) ? res.data.content : []
      total.value = res.data.totalElements || 0
      console.log('获取到的分类列表数据:', tableData.value.length, '条记录')
    } else {
      // 如果返回的数据无效，设置为空数组
      tableData.value = []
      total.value = 0
      ElMessage.error(res?.message || '获取分类列表失败')
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    // 确保在发生错误时设置为空数组
    tableData.value = []
    total.value = 0
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 新增分类
const handleAdd = () => {
  form.value = {
    id: null,
    name: '',
    description: ''
  }
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除分类
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该分类吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      console.log('开始删除分类, ID:', row.id)
      loading.value = true

      const res = await request.delete(`/categories/${row.id}`)

      if (res.code === 200) {
        ElMessage.success('删除成功')
        console.log('删除成功，准备刷新数据...')

        // 延迟一点时间再刷新，确保后端有足够时间清理缓存
        setTimeout(() => {
          // 使用强制刷新模式，带时间戳参数
          getList(true)
        }, 500)
      } else {
        loading.value = false
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      loading.value = false
      console.error('删除分类失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    console.log('用户取消了删除操作')
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (form.value.id) {
          res = await request.put(`/categories/${form.value.id}`, form.value)
        } else {
          res = await request.post('/categories', form.value)
        }

        if (res.code === 200) {
          ElMessage.success(form.value.id ? '更新成功' : '新增成功')
          dialogVisible.value = false
          getList()
        } else {
          ElMessage.error(res.message || (form.value.id ? '更新失败' : '新增失败'))
        }
      } catch (error) {
        console.error('提交表单失败:', error)
        ElMessage.error(form.value.id ? '更新失败' : '新增失败')
      }
    }
  })
}

// 分页处理
const handleSizeChange = (val) => {
  pageParams.value.size = val
  pageParams.value.page = 1
  getList()
}

const handleCurrentChange = (val) => {
  pageParams.value.page = val
  getList()
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  const date = new Date(datetime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}
</style>